package com.new2i.service.impl;
 
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; 

import com.new2i.dao.able.EmrNeonatusDao;
import com.new2i.dao.able.EmrPicDao;
import com.new2i.model.EmrNeonatusEntity;
import com.new2i.model.EmrPicEntity;
import com.new2i.service.able.EmrService;
import com.new2i.util.CsvFileParseUtil;
import com.new2i.util.EncryptionUtil;
import com.new2i.util.QiniuUptokenGenUtil;
import com.new2i.util.QiniuUptokenGenUtil.BucketNameEnum;
import com.qiniu.util.StringUtils; 

/**
 * 病历相关业务逻辑实现类
 * 
 * @since 2015/09/03
 * @author 2i
 *
 */
@Service("EmrService")
public class EmrServiceImpl implements EmrService{
 
	private static long TIMESTAMP = 0;
	 
	private static String Qiniu_Uptoken = "";
	
	private static Logger logger = Logger.getLogger(EmrServiceImpl.class);

	@Autowired
	private EmrPicDao mEmrPicDao;
	
	@Autowired
	private EmrNeonatusDao mEmrNeonatusDao;
	
	@Override
	public HashMap<String, Object> getQiniuMchUptoken() {
		long current = System.currentTimeMillis();
		if (TIMESTAMP == 0 || current - TIMESTAMP > 1800) { //刷新机制，每过1800s从七牛刷新一次uptoken,减少token请求数
			Qiniu_Uptoken = QiniuUptokenGenUtil.getUptoken(BucketNameEnum.Mch.getString());
			TIMESTAMP = current;
		} 
		HashMap<String, Object> map = new HashMap<>();
		map.put("uptoken", Qiniu_Uptoken);
		return map;
	}

	@Override
	public HashMap<String, Object> insertEmrNeonatus(EmrNeonatusEntity emr) {
		HashMap<String, Object> rHashMap = new HashMap<String, Object>();
		if(emr.getDoctor_id() == 0 || emr.getUser_id() == 0) {
			rHashMap.put("code", 311);
			rHashMap.put("err_msg", "未指定用户");
		}
		Date now = new Date();
		emr.setCreate_date(now);
		emr.setUpdate_date(now);
		emr.setExist_status(0);
		emr.setEmr_uuid(EncryptionUtil.getTimestampToken());
		try { 
			EmrNeonatusEntity rEmr = mEmrNeonatusDao.insertEmrNeonatus(emr);
			int emr_id = rEmr.getEmr_neonatus_id();
			rHashMap.put("emr_neonatus_id", emr_id);
			rHashMap.put("emr_uuid", rEmr.getEmr_uuid());  
			String emrpicStr = emr.getEmrpic_urls();
			if(emrpicStr == null || emrpicStr.length() <= 0) {  
				return rHashMap;
			}  
			HashSet<String> keySet = new HashSet<String>();
			String urlStrs[] = emrpicStr.split(",");
			for(String urlStr : urlStrs) {
				if(urlStr.length() <= 0) {
					continue;
				}
				logger.debug("urlStr==>"+urlStr); 
				String fileUrl = urlStr.replaceAll(".png", ".csv").replaceAll(".jpg", ".csv"); 
				logger.debug("picUrl==>"+fileUrl);
				HashMap<String, String> epInfo = CsvFileParseUtil.toHashMapByUrlString(fileUrl); 
				if(epInfo == null || epInfo.isEmpty()) {
					continue;
				}		 
				String imageType = epInfo.get("SessionItem.ImageOf"); 
				String imageLens = epInfo.get("SessionItem.ImageLens");  
				logger.debug("imageType==>"+imageType);
				logger.debug("imageLens==>"+imageLens);
				EmrPicEntity emrpic = new EmrPicEntity();
				if("OD".equals(imageType)) {
					emrpic.setIndex_type(1);
				}else { 
					emrpic.setIndex_type(0);
				} 
				logger.debug("epInfo==>" + epInfo);
				emrpic.setPic_url(urlStr);  
				emrpic.setCreate_date(now);
				emrpic.setUpdate_date(now);
				emrpic.setExist_status(0);
				emrpic.setEmr_type(3);
				emrpic.setEmr_id(emr_id); 
				keySet.add(imageType + ":" + imageLens);
				mEmrPicDao.insertEmrPic(emrpic);
			}  
			String resultDesc = StringUtils.join(keySet.toArray(), ",");  
			logger.debug("resultDesc==>"+resultDesc); 
			emr.setResult_desc(resultDesc);
			emr.setEmr_neonatus_id(emr_id);
			mEmrNeonatusDao.updateEmrNeonatusById(emr);   
		}catch (Exception e){
			logger.error(e.getLocalizedMessage());
			rHashMap.put("code", 321);
			rHashMap.put("err_msg", "创建病历失败");
			return rHashMap;
		} 
		return rHashMap;
	}

	@Override
	public HashMap<String, Object> updateEmrNeonatusById(EmrNeonatusEntity emr) {
		HashMap<String, Object> rHashMap = new HashMap<String, Object>();
		if(emr.getDoctor_id() == 0 || emr.getUser_id() == 0) {
			rHashMap.put("code", 311);
			rHashMap.put("err_msg", "未指定用户");
		}   
		if(emr.getEmr_neonatus_id() == 0) {
			rHashMap.put("code", 312);
			rHashMap.put("err_msg", "未指定病历");
		} 
		Date now = new Date(); 
		emr.setUpdate_date(now);  
		try { 
			EmrNeonatusEntity rEmr = mEmrNeonatusDao.insertEmrNeonatus(emr);
			rHashMap.put("emr_neonatus_id", rEmr.getEmr_neonatus_id());
			rHashMap.put("emr_uuid", rEmr.getEmr_uuid());  
			return rHashMap;
		}catch (Exception e){
			logger.error(e.getLocalizedMessage());
			rHashMap.put("code", 321);
			rHashMap.put("err_msg", "修改病历失败");
		}   
		return rHashMap;
	}

	@Override
	public HashMap<String, Object> getEmrInfoById(EmrNeonatusEntity emr) {
		HashMap<String, Object> rHashMap = new HashMap<String, Object>(); 
		int emr_id = emr.getEmr_neonatus_id();           
		if(emr_id == 0) {
			return rHashMap;
		}  
		rHashMap = mEmrNeonatusDao.getEmrInfoById(emr_id);  
		List<HashMap<String, Object>> osUrlList = new ArrayList<HashMap<String, Object>>();
		List<HashMap<String, Object>> odUrlList = new ArrayList<HashMap<String, Object>>(); 
		// 病历图片json array
		String urlStrs = (String) rHashMap.get("emrpic_urls");
		if (urlStrs != null) {
			String contents[] = urlStrs.split("~");
			for (String content : contents) {
				// 病历图片json info
				if (content.startsWith(",")) {
					content = content.substring(1, content.length());
				}
				String values[] = content.split(",");
				HashMap<String, Object> pic_map = new HashMap<String, Object>();
				int emr_pic_id = Integer.valueOf(values[0]);
				int index_type = Integer.valueOf(values[1]);
				int source = Integer.valueOf(values[2]);
				int emrpic_type = Integer.valueOf(values[3]);
				String emrpic_url = values.length > 4 ? values[4] : "";
				String pic_desc = values.length > 5 ? values[5] : "";
				pic_map.put("emr_pic_id", emr_pic_id);
				pic_map.put("index_type", index_type);
				pic_map.put("source", source);
				pic_map.put("pic_type", emrpic_type);
				pic_map.put("pic_url", emrpic_url);
				pic_map.put("pic_desc", pic_desc); 
				if (index_type == 1)
					osUrlList.add(pic_map);
				else
					odUrlList.add(pic_map);
			}
			rHashMap.put("od_urls", odUrlList);
			rHashMap.put("os_urls", osUrlList); 
			rHashMap.remove("emrpic_urls");
		} 
		return rHashMap;
	}

	@Override
	public HashMap<String, Object> syncEmrNeonatusItem(EmrNeonatusEntity emr) {
		HashMap<String, Object> rHashMap = new HashMap<String, Object>();
		int doctor_id = emr.getDoctor_id();
		int user_id = emr.getUser_id(); 
		if(user_id == 0 || doctor_id == 0) {
			rHashMap.put("code", 311);
			rHashMap.put("err_msg", "未指定用户");
		}   

		String emrpicStr = emr.getEmrpic_urls();
		if(emrpicStr == null || emrpicStr.length() <= 0) { 
			rHashMap.put("code", 313);
			rHashMap.put("err_msg", "上传图片路径无效");
		}
		logger.debug("emrpicStr==>"+emrpicStr); 
		String[] urlStrs = emrpicStr.split(","); 
		logger.debug("urlStrs==>" + urlStrs);
		HashSet<String> keySet = new HashSet<String>();
		int emr_id = 0;
		try { 
			Date now = new Date();
			emr.setUpdate_date(now);
			HashMap<String, Object> topEmrInfo = mEmrNeonatusDao.getTopEmrByDU(doctor_id, user_id); 
			if(topEmrInfo == null || topEmrInfo.isEmpty()) {
				emr.setCreate_date(now);
				emr.setExist_status(0);
				emr.setEmr_uuid(EncryptionUtil.getTimestampToken());
				EmrNeonatusEntity rEmr = mEmrNeonatusDao.insertEmrNeonatus(emr);
				emr_id = rEmr.getEmr_neonatus_id();
				logger.debug("top emr is null emr id==>" + emr_id);  
				rHashMap.put("emr_neonatus_id", emr_id);
				rHashMap.put("emr_uuid", rEmr.getEmr_uuid()); 
			} else { 
				String sEmrId = topEmrInfo.get("emr_neonatus_id").toString();
				logger.debug("top emr not null==>" + sEmrId); 
				emr_id = Integer.parseInt(sEmrId);
				logger.debug("emr_id==>" + emr_id); 

			} 
			for(String urlStr : urlStrs) {
				if(urlStr.length() <= 0) {
					continue;
				}
				logger.debug("urlStr==>"+urlStr); 
				String fileUrl = urlStr.replaceAll(".png", ".csv").replaceAll(".jpg", ".csv"); 
				logger.debug("picUrl==>"+fileUrl);
				HashMap<String, String> epInfo = CsvFileParseUtil.toHashMapByUrlString(fileUrl); 
				if(epInfo == null || epInfo.isEmpty()) {
					continue;
				}		 
				String imageType = epInfo.get("SessionItem.ImageOf"); 
				String imageLens = epInfo.get("SessionItem.ImageLens");  
				logger.debug("imageType==>"+imageType);
				logger.debug("imageLens==>"+imageLens);
				EmrPicEntity emrpic = new EmrPicEntity();
				if("OD".equals(imageType)) {
					emrpic.setIndex_type(1);
				}else { 
					emrpic.setIndex_type(0);
				} 
				logger.debug("epInfo==>"+epInfo); 
				emrpic.setDoctor_id(doctor_id);
				emrpic.setPic_url(urlStr);  
				emrpic.setCreate_date(now);
				emrpic.setUpdate_date(now);
				emrpic.setExist_status(0);
				emrpic.setEmr_type(3);
				emrpic.setEmr_id(emr_id); 
				keySet.add(imageType + ":" + imageLens);
				mEmrPicDao.insertEmrPic(emrpic);
			} 
			String resultDesc = StringUtils.join(keySet.toArray(), ",");  
			logger.debug("resultDesc==>"+resultDesc); 
			emr.setResult_desc(resultDesc);
			emr.setEmr_neonatus_id(emr_id);
			mEmrNeonatusDao.updateEmrNeonatusById(emr); 
			rHashMap.put("emr_neonatus_id", emr_id);
			rHashMap.put("msg", "成功同步" + urlStrs.length + "张图片");
		} catch (Exception e) {
			logger.error(e.getLocalizedMessage());
			rHashMap.put("code", 323);
			rHashMap.put("err_msg", "同步图片失败");
		}
		return rHashMap;
	}

}
